package com.venus.mq.storage;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by qts on 2018/12/7.
 */
public class test {

    private static int  length = 1000;

    public static void main(String[] args) throws Exception {
        // 为了以可读可写的方式打开文件，这里使用RandomAccessFile来创建文件。
        FileChannel fc = new RandomAccessFile("/Users/qts/Desktop/test.txt", "rw").getChannel();
        fc.position(20);
        String s = "我的测试";
        fc.write(ByteBuffer.wrap(s.getBytes("UTF-8")));
        //注意，文件通道的可读可写要建立在文件流本身可读写的基础之上
        MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, length);
        //读取文件中间6个字节内容
        int length  = s.getBytes("UTF-8").length;
        System.out.print("长度:"+length);
        byte[] bytes = new byte[length];
        fc.read(ByteBuffer.wrap(bytes),20);
        System.out.print(new String(bytes));
        fc.close();
    }
}
